/*
 * IBP - Technology architecture for real-time transaction
 * author	: calvin
 * email	: calvinwilliams@163.com
 *
 * Licensed under the LGPL v2.1, see the file LICENSE in base directory.
 */

#include "ibas_in.h"

static int HttpClient( struct IbasEnv *p_env , char *req )
{
	struct NetAddress	netaddr ;
	struct HttpEnv		*http = NULL ;
	
	char			*statuscode = NULL ;
	int			statuscode_len ;
	char			*reasonphrase = NULL ;
	int			reasonphrase_len ;
	char			*body = NULL ;
	int			body_len ;
	
	int			nret = 0 ;
	
	memset( & netaddr , 0x00 , sizeof(struct NetAddress) );
	QueryNetIpByHostName( p_env->ibas_conf.ibas.server.ip , netaddr.ip , sizeof(netaddr.ip) );
	QueryNetPortByServiceName( p_env->ibas_conf.ibas.server.port , "tcp" , & (netaddr.port) );
	if( netaddr.port == 0 )
	{
		printf( "*** ERROR : port[%s][%d] invalid\n" , p_env->ibas_conf.ibas.server.port , netaddr.port );
		return -1;
	}
	
	http = CreateHttpEnv() ;
	if( http == NULL )
	{
		printf( "*** ERROR : CreateHttpEnv failed , errno[%d]\n" , errno );
		return -1;
	}
	
	nret = HttpRequest( & netaddr , http , 60 , "%s" , req ) ;
	if( nret )
	{
		printf( "*** ERROR : HttpRequest failed[%d] , errno[%d]\n" , nret , errno );
		DestroyHttpEnv( http );
		return nret;
	}
	
	statuscode = GetHttpHeaderPtr_STATUSCODE( http , & statuscode_len ) ;
	reasonphrase = GetHttpHeaderPtr_REASONPHRASE( http , & reasonphrase_len ) ;
	if( STRNCMP( statuscode , != , HTTP_OK_S , 2 ) )
	{
		printf( "%.*s %.*s\n" , statuscode_len , statuscode , reasonphrase_len , reasonphrase );
	}
	else
	{
		body = GetHttpBodyPtr( http , & body_len );
		if( body )
		{
			if( body[body_len-1] != '\n' )
				printf( "%.*s\n" , body_len , body );
			else
				printf( "%.*s" , body_len , body );
		}
	}
	
	DestroyHttpEnv( http );
	
	return nstoi(statuscode,statuscode_len);
}

int ShowStatus( struct IbasEnv *p_env )
{
	char			req[] = "GET " URI_SHOW_STATUS " HTTP/1.0" HTTP_RETURN_NEWLINE HTTP_RETURN_NEWLINE ;
	
	return HttpClient( p_env , req );
}

int ShowBbStat( struct IbasEnv *p_env )
{
	char			req[] = "GET " URI_SHOW_BBSTAT " HTTP/1.0" HTTP_RETURN_NEWLINE HTTP_RETURN_NEWLINE ;
	
	return HttpClient( p_env , req );
}

int ShowBbDetail( struct IbasEnv *p_env )
{
	char			req[] = "GET " URI_SHOW_BBDETAIL " HTTP/1.0" HTTP_RETURN_NEWLINE HTTP_RETURN_NEWLINE ;
	
	return HttpClient( p_env , req );
}

